<?
/**
 * VoiceOne Settings/Tool/application/edit
 *
 * Frontend to provide access to the tech system in voiceone.
 * @package voiceone
 * @subpackage  settings_tool
 */
  include ("../../../../admin/config/cfg.php");
  global $cwlang, $cwLanguage; 
  require_once("$absBasePath/lib/xajax/xajax.inc.php"); 
  sajax_init();
  
  //================ XAJAX ================
	function roll(){
    global $relBasePath,$cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Build response
    $html=" <img src=\"".$relBasePath."public/img/ico-progress.gif"."\" alt=\"loading\" /><span>".T_("loading")."</span>";
    $objResponse->addAssign("loading","innerHTML",$html);
    // Return the xajaxResponse object
    return $objResponse->getXML(); 
  }
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Extract form's params
    $id=$formData["id"];
    $label=$formData["label"];
    $name=$formData["name"];
    $extension=$formData["extension"];
    $description=$formData["description"];
    $macro=$formData["macro"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">&nbsp;&nbsp;";
    // Retrieve all applications
    $appArr=$asterisk->getApplication(0);
    if(is_array($appArr)){
      foreach($appArr as $app) {
        if($id==$app["id"]) continue;
        $appLabelArr[]=$app["label"];
      }
    }
    // Retrieve all extensions
    $extArr=$asterisk->getExtension(0);
    if(is_array($extArr)){
      foreach($extArr as $e){ 
        if($id==$e["entity_id"]) continue;
        $eExtArr[]=$e["extension"];
      }
    }
    // Check Label ((not null)&&(unique))
    $labelErr=false;
    if($label=="") { 
      //label cannot be null
      $errOut[]= T_("Name cannot be null");
      $objResponse->addAssign("labelErr","innerHTML",$imgErr);
      $labelErr=true;  
    }else if((is_array($appLabelArr))&&(in_array($label,$appLabelArr))){
      //label must be unique
      $errOut[]= T_("Name already exists. Please change it");
      $objResponse->addAssign("labelErr","innerHTML",$imgErr);
      $labelErr=true;
    }
    if($labelErr===false) $objResponse->addAssign("labelErr","innerHTML","");
    // Check Extension ((not null)&&(unique))
    $extenErr=false;
    if($extension=="") { 
      //extension cannot be null
      $errOut[]= T_("Extension cannot be null");
      $objResponse->addAssign("extenErr","innerHTML",$imgErr);
      $extenErr=true;  
    }else if((is_array($eExtArr))&&(in_array($extension,$eExtArr))){
      //extension must be unique
      $errOut[]= T_("Extension already exists. Please change it");
      $objResponse->addAssign("extenErr","innerHTML",$imgErr);
      $extenErr=true;
    }
    if($extenErr===false) $objResponse->addAssign("extenErr","innerHTML","");
    // Check Port (not null)
    $macroErr=false;
    if($macro==""){
      //macro cannot be null
      $errOut[]=T_("Macro cannot be null. Please select a macro to execute");
      $objResponse->addAssign("macroErr","innerHTML",$imgErr);
      $macroErr=true;
    }
    if($macroErr===false) $objResponse->addAssign("macroErr","innerHTML","");
    // Process Form
    if(isset($errOut)){
      $error="<div class=\"AlertBad\"><ul>";
      foreach($errOut as $err) $error.="<li>".$err."</li>";
      $error.="</ul></div>";
      $objResponse->addAssign("alert","innerHTML",$error);
      $objResponse->addAssign("loading","innerHTML","");
    }else{
      $objResponse->addAssign("loading","innerHTML",""); 
      $objResponse->addScript(" document.getElementById('mainform').submit(); ");
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();  
  }
  $xajax = new xajax();
  $xajax->registerFunction("roll");
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();
  
  //=================== POST ==================
  if (count($_POST)>0) { 
    $entry=Array(
      "id" => $_POST["id"],
      "name" => $_POST["name"],
      "label" => $_POST["label"],
      "description" => $_POST["description"], 
      "extension" => $_POST["extension"], 
      "code" => $_POST["code"],  
      "groups" => $_POST["group"],  
      "macro" => $_POST["macro"]  
    ); 
    //merge the parameter
    if (is_array($_POST["macro_param"]))
    foreach ($_POST["macro_param"] as $k=>$v) $p.="$k=$v|";
    $p=substr($p,0,-1);
    $entry["parameter"]=$p;
    //save the group informations
    $ret=$asterisk->putApplication($entry);
    if ($ret>0){
      if($_POST["id"]=="") $alert="<div class=\"AlertGood\">".T_("The Application has been created")."</div>";
      else $alert="<div class=\"AlertGood\">".T_("The Application has been modified")."</div>";
    }else{ 
      if($_POST["id"]=="") $alert="<div class=\"AlertBad\">".T_("The Application hasn't been created")."</div>";
      else $alert="<div class=\"AlertBad\">".T_("The Application hasn't been modified")."</div>";
    }
    goToMainPage($alert); 
  }
  
  //================ PAGE LOGIC ================
  //inizialize Page Title
  $pageTitle=T_("New Application");
  $ret=$asterisk->getApplication(0);
  if ($err=$asterisk->getError()) die("Error: $err");
  if (is_array($ret)) 
  foreach($ret as $a) {
    $appList.="<li><a href=\".?id=".$a["id"]."\">".$a["label"]."</a></li>";
    //if modify, read the group informations
    if (isset($_GET["id"]) and $a["id"]==$_GET["id"]) {
      $id=$a["id"];
      $name=$a["name"];
      $label=$a["label"];
      $description=$a["description"];
      $extension=$a["extension"];
      $code=$a["code"];
      $macro=$a["macro"];
      $parameter=$a["parameter"];
      $groups=$a["groups"];
      //set Page Title
      $pageTitle=sprintf(T_("Edit application: %s"),$label );
    } 
  }

  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../admin/lib/xajax/"); 
  ?>

  <?$sel="application";include("../../navigation.php");?>
  
  <div class="SectionHeader">
    <div id="loading" style="float: right;"></div>
    <h1><?=$pageTitle?></h1>
    <h3><a href="../" class="admin" ><?=T_("Return without save")?></a></h3>
  </div>
  <div id="alert"></div>
  <div id="basic_form">
    <form id="mainform" action="<?=$PHP_SELF?>" method="post">
      <p class="blockintro"><?=T_("Edit your the settings of this application")?></p>
      <div class="block">
        <dl>
          <dt class="required"><?=T_("Name")?>:</dt>
          <dd><input type="textfield" id="label" name="label" value="<?=$label?>" /><span id="labelErr"></span> <span class="help"> <?=T_("Detailed name, i.e. <strong>Call Forwarding</strong>")?></span></dd>
        <? if (isset($_GET["id"])){ ?>
            <dt class="required"><?=T_("Key")?>:</dt>
            <dd><input type="textfield" id="name" name="name" value="<?=$name?>" disabled="disabled"/><input type="hidden" name="name" value="<?=$name?>" /> <span class="help"><?=T_("Internal name")?></span></dd>
        <? } ?>  
          <dt class="required"><?=T_("Description")?>:</dt>
          <dd><textarea id="description" name="description" style="width: 500px"><?=$description?></textarea></dd>
          <dt class="required"><?=T_("Extension")?>:</dt>
          <dd><input type="textfield" id="extension" name="extension" value="<?=$extension?>" /><span id="extenErr"></span> <span class="help"><?=T_("Write the extension catch, i.e. <strong>*72</strong>")?></span></dd>
       <!--   
          <dt class="required"><?=T_("Code")?>:</dt>
          <dd><textarea id="code" name="code" wrap="off" style="width: 500px; height: 50px"><?=$code?></textarea></dd>
          <dt class="required"></dt>
          <dd><span class="help">You can write lines like: <strong>GOTO DefaultRule|999999|1</strong></span></dd>
        -->
        </dl>
        <input type="hidden" name="id" value="<?=$id?>" />
      </div>

      <?echo listMacro($js, $macro, $parameter);?>      
      
      <?echo listGroup(GROUP_OF_APPLICATION, $js, $groups);?>      

      <div class="action">
        <?if ($_GET["id"]!="") {?><input type="hidden" name="id" value="<?=$id?>" /><?}?>
        <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/></a>
        <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick=" document.getElementById('alert').innerHTML=''; xajax_processFormData(xajax.getFormValues('mainform')); "/></a>
      <!--  
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Annulla" onclick="location.href='../'; return false;"/>
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Salva" />
       -->
      </div> 
    </form>
  </div>      
  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start(); 
  ?>
        <div class="Sidebar">
          <h1><?=T_("Informations")?></h1>
          <p><?=T_("To be done...")?></p>
        </div>
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
 	sajax_handle_client_request();

  $smarty->assign("section", "application");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->assign("ajax", $js);
  $smarty->display('settings.tpl');
?>
